package com.yunao.service.report.esou;

import com.lowagie.text.*;
import com.yunao.commons.serachcore.core.bean.*;
import com.yunao.commons.serachcore.core.help.GroupField;
import com.yunao.commons.serachcore.core.help.MediaType;
import com.yunao.commons.serachcore.core.help.SearchFiled;
import com.yunao.entity.AloneReport;
import com.yunao.service.ReportService;
import com.yunao.service.report.Convert;
import com.yunao.service.report.DateUtil;
import com.yunao.service.report.bean.SearchBeans;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * 日报
 *
 * @author glt
 *
 */
public class ReportDaily2 {

	private int id;
	private String name;
	private String word;
	private String query;
	private String organId;
	private AloneReport aloneReport;
	// 标题
	private String title;
	// 编号
	private String number;
	// 副标题
	private String subtitleLeft;
	private String subtitleRight;
	// 大数据综述
	private String overviewDesc;
	private String overviewImgs;

	private Clusters beansdl;
	private Clusters beanssdzw;
	private Clusters beanssd;
	private ReportService reportService;


	public ReportDaily2(AloneReport aloneReport,ReportService reportService) {
		this.id = aloneReport.getId();
		this.name = aloneReport.getName();
		this.word = aloneReport.getWord();
		this.query = aloneReport.getQuery();
		this.organId=aloneReport.getSubjectOrganizationId();
		this.reportService = reportService;
		this.aloneReport = aloneReport;
	}

	public String createMailc() throws Exception {
		System.out.println("reproting......");
		// 自动报告创建位置
		String filePath = ItextUtil.filepath(id);
		String docPath = filePath + System.currentTimeMillis() + ".doc";
		System.out.println(docPath);
		File file = new File(docPath);
		if (!file.exists())
			file.createNewFile();

		// 自动报告的时间，最近一天
		long[] time = new long[2];
		time=DateUtil.getSearchTime("1");
		System.out.println("即时报告区间-："+time[0]+","+time[1]);

		// 创建 document
		Document doc = ItextUtil.open(docPath);

		// 日报标题
		title = name + "大数据日报";
		Paragraph headTitle = ItextUtil.createParagraph(title,
				ItextUtil.createStyle(
						ItextUtil.FAMILY_TITLE,
						28,
						ItextUtil.COLOR_RED,
						Font.BOLD),
				Element.ALIGN_CENTER,
				10,
				10);
		doc.add(headTitle);

		// 日报编号
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		number = "〔" + c.get(Calendar.YEAR) + "〕" + id + c.get(Calendar.MONTH) + c.get(Calendar.DAY_OF_YEAR) + "号";
		Paragraph headNumber = ItextUtil.createParagraph(number, ItextUtil.createStyle(ItextUtil.FAMILY_TITLE, 18,
				ItextUtil.COLOR_BLACK), Element.ALIGN_CENTER, 5, 5);
		doc.add(headNumber);

		// 日报副标题
		subtitleLeft = "云奥大数据";
		subtitleRight = DateUtil.getCurrDate("yyyy年MM月dd日");
		String subtitle = subtitleLeft + "                                               " + subtitleRight;
		Paragraph headSubtitle = ItextUtil.createParagraph(subtitle, ItextUtil.createStyle(ItextUtil.FAMILY_TITLE, 14,
				ItextUtil.COLOR_BLACK, Font.BOLD, Font.UNDERLINE), Element.ALIGN_CENTER, 5, 15);
		doc.add(headSubtitle);

		/*
		 * 大数据综述
		 */
		Paragraph overviewNav = ItextUtil.createParagraph("一、大数据概况", ItextUtil.createStyle(ItextUtil.FAMILY_TITLE, 18,
				ItextUtil.COLOR_BLACK, Font.BOLD), Element.ALIGN_LEFT, 10, 5);
		doc.add(overviewNav);

		//媒体类型大数据概况趋势图
		Cubes cBeans = trend(word, query, time);
		if(cBeans!=null){
			if(cBeans.getSize()>0){
				cBeans.sortByValue();
				String maxDate = "";
				String maxDate1 = "";
				long maxNum = 0 ;
				if(cBeans.size()>3){
					maxNum = cBeans.get(0).getValue();
					long timeLong1 = Convert.getLong(cBeans.get(1).getKey());
					maxDate = DateUtil.date2Str(new Date(timeLong1), "yyyy年MM月dd日 HH时mm分");
					long timeLong2 = Convert.getLong(cBeans.get(2).getKey());
					maxDate1 = DateUtil.date2Str(new Date(timeLong2), "yyyy年MM月dd日 HH时mm分");
				}

				Clusters beans = query(word, query, time,"","");
				String TI1 = "";
				String TI2 = "";
				if(beans!=null&&beans.getData().size()>2){
					TI1 = beans.get(0).getDocs().get(0).getTitle();
					TI2 = beans.get(1).getDocs().get(0).getTitle();
					if(TI1.length()<5){
						int a =  beans.get(0).getDocs().get(0).getSummary().length()>15?15: beans.get(0).getDocs().get(0).getSummary().length();
						TI1 = beans.get(0).getDocs().get(0).getSummary().substring(0,a-1);
					}

					if(TI2.length()<5){
						int a =  beans.get(0).getDocs().get(0).getSummary().length()>15?15: beans.get(0).getDocs().get(0).getSummary().length();
						TI2 = beans.get(0).getDocs().get(0).getSummary().substring(0,a-1);
					}
				}

				overviewImgs = JFreeChartUtil.drawLine(cBeans, "今日媒体类型大数据趋势图", filePath);
				Image img = ItextUtil.createImage(overviewImgs, Element.ALIGN_CENTER, 450, 160);
				doc.add(img);
				if(cBeans.getSize()!=0) {
					cBeans.sortByValue();
				}
				if(cBeans.size()>3){
					this.overviewDesc = "本日以关键词“"+word+"”对"+DateUtil.long2Str(time[0], "yyyy年MM月dd日HH时mm分")+"至"+DateUtil.long2Str(time[1], "yyyy年MM月dd日HH时mm分")
							+"以来，互联网上的相关网情进行了整理分析，共发现相关网情"+ cBeans.getTotal() +"条。当日高峰时段分别是" + maxDate
							+ "和" + maxDate1 + "，高峰时段共监测到" + cBeans.get(0).getValue()+ "条信息，引导高峰的信息是：1."
							+ TI1+"。2."+TI2+"。";
				}else{
					this.overviewDesc = "";
				}

				Paragraph overviewDesc = ItextUtil.createParagraph(this.overviewDesc, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
						ItextUtil.COLOR_BLACK, Font.NORMAL), Element.ALIGN_LEFT, 3, 3, 36);
				doc.add(overviewDesc);
			}
		}

		/*
		 * 重点新闻媒体关注热点
		 */
		beansdl = query(word, this.query, time, "domain_level", "中央重点,省级重点,地方城市");
		Paragraph infoNav = ItextUtil.createParagraph("二、重点新闻媒体关注热点", ItextUtil.createStyle(ItextUtil.FAMILY_TITLE, 18,
				ItextUtil.COLOR_BLACK, Font.BOLD), Element.ALIGN_LEFT, 10, 5);
		doc.add(infoNav);
		int num = 0;
		if(beansdl!=null&&beansdl.getSize()>0){
			for (int i = 0; i < beansdl.getData().size(); i++) {
				Article bean = beansdl.get(i).getDocs().get(0);
				if(bean!=null&&!bean.equals("")){
					String title = (i + 1) + ". " + bean.getTitle().replaceAll("<[/]?em>", ""), source = bean.getDomainSource(), pubdate = bean
							.getPubdate().toString(), summary = bean.getSummary().replaceAll("<[/]?em>", ""), href = bean.getUrl();
					String links;
					try {
						if(href.indexOf("https://")==-1){
							links = href.substring(href.indexOf("http://") + 7);
							links = links.substring(0, links.indexOf("/"));
						}else{
							links = href.substring(href.indexOf("https://") + 8);
							links = links.substring(0, links.indexOf("/"));
						}
					} catch (Exception e) {
						links = href;
					}
					// 标题
					Paragraph infoLinks1 = ItextUtil.createParagraph("", ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 14,
							ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 0, 36);
					Anchor anchor1 = ItextUtil.createAnchor(title, href, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
							ItextUtil.COLOR_BLUE));
					infoLinks1.add(anchor1);
					doc.add(infoLinks1);
//				Paragraph infoTitle = ItextUtil.createParagraph(title, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 14,
//						ItextUtil.COLOR_BLACK, Font.BOLD), Element.ALIGN_LEFT, 5, 0, 36);
//				doc.add(infoTitle);
					// 来源
					Paragraph infoSource = ItextUtil.createParagraph("【来源】" + source + "   " + pubdate, ItextUtil.createStyle(
							ItextUtil.FAMILY_TEXT, 12, ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 0, 36);
					doc.add(infoSource);

					// 链接
					Paragraph infoLinks = ItextUtil.createParagraph("【链接】", ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
							ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 0, 36);
					Anchor anchor = ItextUtil.createAnchor(links, href, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
							ItextUtil.COLOR_BLUE));
					infoLinks.add(anchor);
					doc.add(infoLinks);
					// 摘要
					Paragraph infoSummary = ItextUtil.createParagraph("【摘要】" + summary, ItextUtil.createStyle(
							ItextUtil.FAMILY_TEXT, 12, ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 10, 36);
					doc.add(infoSummary);
					num++;
					if(num==10)
						break;
				}

			}
		}
		/**
		 * 		政务网站关注热点
		 */
		beanssdzw = query(word, this.query, time, SearchFiled.MEDIA_TYPE.toLowerCase(), MediaType.GOVERNMENT.toString());
		Paragraph infoNavdm = ItextUtil.createParagraph("三、政务网站关注热点", ItextUtil.createStyle(ItextUtil.FAMILY_TITLE, 18,
				ItextUtil.COLOR_BLACK, Font.BOLD), Element.ALIGN_LEFT, 10, 5);
		doc.add(infoNavdm);
		num = 0;
		if(beanssdzw!=null&&beanssdzw.getSize()>0){
			for (int i = 0; i < beanssdzw.getData().size(); i++) {
				Article bean = beanssdzw.getData().get(i).getDocs().get(0);
				if(bean!=null&&!bean.equals("")){
					String title = (i + 1) + ". " + bean.getTitle().replaceAll("<[/]?em>", ""), source = bean.getDomainSource(), pubdate = bean
							.getPubdate().toString(), summary = bean.getSummary().replaceAll("<[/]?em>", ""), href = bean.getUrl();
					String links;
					try {
						if(href.indexOf("https://")==-1){
							links = href.substring(href.indexOf("http://") + 7);
							links = links.substring(0, links.indexOf("/"));
						}else{
							links = href.substring(href.indexOf("https://") + 8);
							links = links.substring(0, links.indexOf("/"));
						}
					} catch (Exception e) {
						links = href;
					}
					// 标题
					Paragraph infoLinks1 = ItextUtil.createParagraph("", ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 14,
							ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 0, 36);
					Anchor anchor1 = ItextUtil.createAnchor(title, href, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
							ItextUtil.COLOR_BLUE));
					infoLinks1.add(anchor1);
					doc.add(infoLinks1);
//				Paragraph infoTitle = ItextUtil.createParagraph(title, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 14,
//						ItextUtil.COLOR_BLACK, Font.BOLD), Element.ALIGN_LEFT, 5, 0, 36);
//				doc.add(infoTitle);
					// 来源
					Paragraph infoSource = ItextUtil.createParagraph("【来源】" + source + "   " + pubdate, ItextUtil.createStyle(
							ItextUtil.FAMILY_TEXT, 12, ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 0, 36);
					doc.add(infoSource);

					// 链接
					Paragraph infoLinks = ItextUtil.createParagraph("【链接】", ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
							ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 0, 36);
					Anchor anchor = ItextUtil.createAnchor(links, href, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
							ItextUtil.COLOR_BLUE));
					infoLinks.add(anchor);
					doc.add(infoLinks);
					// 摘要
					Paragraph infoSummary = ItextUtil.createParagraph("【摘要】" + summary, ItextUtil.createStyle(
							ItextUtil.FAMILY_TEXT, 12, ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 10, 36);
					doc.add(infoSummary);
					num++;
					if(num==10)
						break;
				}

			}
		}

		/**
		 * 		两微一端关注热点
		 */

		beanssd = query(word, this.query, time, SearchFiled.MEDIA_TYPE.toLowerCase(), MediaType.WEIBO.toString());

        Paragraph infoNavsd = ItextUtil.createParagraph("四、微博关注热点", ItextUtil.createStyle(ItextUtil.FAMILY_TITLE, 18,
				ItextUtil.COLOR_BLACK, Font.BOLD), Element.ALIGN_LEFT, 10, 5);
		doc.add(infoNavsd);
		num = 0 ;
		if(beanssd!=null&&beanssd.getSize()>0){
			for (int i = 0; i <  beanssd.getData().size(); i++) {
				Article bean = beanssd.getData().get(i).getDocs().get(0);
				if(bean!=null&&!bean.equals("")){
					String title = (i + 1) + ". " + bean.getTitle().replaceAll("<[/]?em>", ""), source = bean.getDomainSource(), pubdate = bean
							.getPubdate().toString(), summary = bean.getSummary().replaceAll("<[/]?em>", ""), href = bean.getUrl();
					String links;
					try {
						if(href.indexOf("https://")==-1){
							links = href.substring(href.indexOf("http://") + 7);
							links = links.substring(0, links.indexOf("/"));
						}else{
							links = href.substring(href.indexOf("https://") + 8);
							links = links.substring(0, links.indexOf("/"));
						}
					} catch (Exception e) {
						links = href;
					}
					// 标题
					Paragraph infoLinks1 = ItextUtil.createParagraph("", ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 14,
							ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 0, 36);
					Anchor anchor1 = ItextUtil.createAnchor(title, href, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
							ItextUtil.COLOR_BLUE));
					infoLinks1.add(anchor1);
					doc.add(infoLinks1);
//				Paragraph infoTitle = ItextUtil.createParagraph(title, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 14,
//						ItextUtil.COLOR_BLACK, Font.BOLD), Element.ALIGN_LEFT, 5, 0, 36);
//				doc.add(infoTitle);
					// 来源
					Paragraph infoSource = ItextUtil.createParagraph("【来源】" + source + "   " + pubdate, ItextUtil.createStyle(
							ItextUtil.FAMILY_TEXT, 12, ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 0, 36);
					doc.add(infoSource);

					// 链接
					Paragraph infoLinks = ItextUtil.createParagraph("【链接】", ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
							ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 0, 36);
					Anchor anchor = ItextUtil.createAnchor(links, href, ItextUtil.createStyle(ItextUtil.FAMILY_TEXT, 12,
							ItextUtil.COLOR_BLUE));
					infoLinks.add(anchor);
					doc.add(infoLinks);
					// 摘要
					Paragraph infoSummary = ItextUtil.createParagraph("【摘要】" + summary, ItextUtil.createStyle(
							ItextUtil.FAMILY_TEXT, 12, ItextUtil.COLOR_BLACK), Element.ALIGN_LEFT, 0, 10, 36);
					doc.add(infoSummary);
					num++;
					if(num==10)
						break;
				}

			}
		}



		doc.close();
		System.out.println("写入成功");
		return docPath;
	}

	public String createHtml() {
		if(overviewDesc==null){
			overviewDesc = "";
		}
		if(overviewImgs==null){
			overviewImgs = "";
		}
		ReportHtml html = new ReportHtml();
		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append("<div class=\"report-wrapper\"><div id=\"report\" class=\"report\">");
		// 报告头部
		String head = html.createHead(title, number, subtitleLeft, subtitleRight);

		sBuilder.append(head);
		// 大数据综述
		String overview = html.createOverview("一、大数据概述 ", overviewDesc, overviewImgs);
		sBuilder.append(overview);
//		// 大数据快讯
//		String news = html.createNews("二、大数据快讯", beans);
//
//		sBuilder.append(news);

		String info = html.createInfo("二、重点新闻媒体关注热点", beansdl);
		sBuilder.append(info);
		String info1 = html.createInfo("三、政务网站关注热点", beanssdzw);
		sBuilder.append(info1);
		String info2 = html.createInfo("四、两微一端关注热点", beanssd);
		sBuilder.append(info2);
		sBuilder.append("</div></div>");
		return sBuilder.toString();
	}
	public String createHtmlword() {
		long[] time = new long[2];
		time[0] = DateUtil.getClearedTime(1);
		time[1] = time[0] + 24 * 60 * 60 * 1000l - 1;
		StringBuilder sBuilder = new StringBuilder();
		String words="关键词云：";
		try{
			words=queryword(word,query ,time);
		}
		catch(Exception e)
		{
			words="服务器关键词云中心发生异常，请通知客服修复该问题";
		}
		sBuilder.append(words);

		return sBuilder.toString();
	}
	public String createHtmlwordc() {
		long[] time = new long[2];
		//time[0] = DateUtil.getClearedTime(1);
		//time[1] = time[0] + 24 * 60 * 60 * 1000l - 1;
		time=DateUtil.getSearchTime("1");
		System.out.println("即时报告区间cloud："+time[0]+","+time[1]);
		StringBuilder sBuilder = new StringBuilder();
		String words="关键词云：";
		try{
			words=queryword(word,query ,time);
		}
		catch(Exception e)
		{
			words="服务器关键词云中心发生异常，请通知客服修复该问题";
		}
		sBuilder.append(words);

		return words;
	}
	public Cubes trend(String word, String query, long[] time) throws Exception {
		Cubes cubes = null;
		try {
			Map<String,String> map = new HashMap();

			map.put("between",time[0]+","+time[1]);
			map.put("word",word);
			map.put("message_type","正文");
			map.put("group",GroupField.DAY.toString());
			map.put("group2",GroupField.MEDIA_TYPE.toString());
			if(aloneReport.getTitle()!=null){
				map.put("title",aloneReport.getTitle());
			}
			if(aloneReport.getAuthor()!=null){
				map.put("author",aloneReport.getAuthor());
			}
			if(aloneReport.getWebattr()!=null){
				map.put("domain",aloneReport.getWebattr());
			}
			cubes = reportService.cube(map);
		} catch (Exception e) {
			System.out.println("检索搜索异常");
		} finally {
			return cubes;
		}
	}
	public Clusters query(String word, String query, long[] time, String fname, String filed) throws Exception {
		Clusters clusters = null;
		try{
			Map map = new HashMap();

			map.put(fname,filed);
			map.put("keywords",word);
			map.put("between",time[0]+","+time[1]);
//        map.put("message_type","正文");
			map.put("distance","0.5");
			map.put("max_group","20");
			if(aloneReport.getTitle()!=null){
				map.put("title",aloneReport.getTitle());
			}
			if(aloneReport.getAuthor()!=null){
				map.put("author",aloneReport.getAuthor());
			}
			if(aloneReport.getWebattr()!=null){
				map.put("domain",aloneReport.getWebattr());
			}
			System.out.println("搜索条件："+map);
			clusters = reportService.cluster(map);

			System.out.println("beans123:"+clusters.getTotal());
		}catch (Exception e){
			System.out.println("检索搜索异常");
		}finally {
			return clusters;
		}

	}

	public String queryword(String word, String query, long[] time) throws Exception {
		String cloud="(大数据摘要见附件)<br>";
		return cloud;
	}

	public static void createFile(String filename,String content){
		try{
			String encoding = "GBK";//设置文件的编码！！UTF-8或者GBK
			OutputStreamWriter outstream = new OutputStreamWriter(new FileOutputStream(filename), encoding);
			System.out.println("filename:\t"+filename);
			PrintWriter writer = new PrintWriter(outstream);
			//writer.format(encoding, null);
			writer.write(content);
			writer.close();
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}

}
